package org.xtlgen;

import org.w3c.dom.Node;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.DOMException;

/**
 * Adapter for a org.w3c.dom.NamedNodeMap, makes it easier to read attributes
 * from the map.
 */
public class ShapeAttributes {
  /**
   * Make a new ShapeAttributes from the given NamedNodeMap.
   */
  public ShapeAttributes(NamedNodeMap namedNodeMap) {
    this.namedNodeMap = namedNodeMap;
  }

  /**
   * Get an attribute value as String.
   *
   * @param name attribute name.
   * @return the value of the attribute.
   * @throws IllegalArgumentException if the attribute is not found or if
   *         unable to read it.
   */
  public String getString(String name) {
    String value = null;
    Node node = namedNodeMap.getNamedItem(name);
    
    if (node == null) {
      throw new IllegalArgumentException("Cannot find required attribute \"" + name + "\".");
    }
    
    try {
      value = node.getNodeValue();
    }
    catch (DOMException e) {
      // Convert to an IllegalArgumentException
      throw new IllegalArgumentException("Cannot retrieve value for attribute \"" + name + "\".");
    }
    
    return value;
  }
  
  /**
   * Get an attribute value as double.
   *
   * @param name attribute name.
   * @return the value of the attribute.
   * @throws IllegalArgumentException if the attribute is not found or if
   *         unable to read it.
   */
  public double getDouble(String name) {
    double value = 0.0;
    String sValue = getString(name);
    
    try {
      value = Double.parseDouble(sValue);
    }
    catch (NumberFormatException e) {
      // Convert to an IllegalArgumentException
      throw new IllegalArgumentException("Cannot convert \"" + sValue + "\" to double.");
    }
    
    return value;
  }

  /*
   * Fields
   */
  private NamedNodeMap namedNodeMap;
}